<template>
  <div>
    <div class="skeleton-group" v-show="!isClose">
      <a-skeleton />
      <a-skeleton />
      <a-skeleton />
      <a-skeleton />
    </div>
    <!-- main -->
    <div v-show="isClose">
      <div class="usage-box">
        <ChartTitle :title="`设备使用概况统计`"></ChartTitle>
        <div class="usage-box-content">
          <div ref="chart" class="pie"></div>
          <div class="discription">
            <div class="discription-item1">
              当前使用者拥有
              <NumberCount
                class="discription-item1-count"
                :data="total"
              ></NumberCount>
              把门锁。
            </div>
            <div class="discription-item2">
              其中已开启
              <NumberCount
                class="discription-item2-count"
                :data="opened"
              ></NumberCount>
              把门锁，已关闭
              <NumberCount :data="closed"></NumberCount>
              把门锁。
            </div>
          </div>
        </div>
      </div>
      <!-- 频繁操作TOP统计 -->
      <div>
        <ChartTitle
          class="operate-top"
          :title="`操作频繁设备TOP5`"
        ></ChartTitle>
        <div>
          <div ref="top" id="top-chart"></div>
        </div>
      </div>
      <div>
        <ChartTitle
          class="situation"
          :title="`最近开关设备情况/次`"
        ></ChartTitle>
        <div style="margin-top: 20px">
          <a-radio-group default-value="a" button-style="solid">
            <a-radio-button value="a" @click="getLineChart(7)">
              近7天
            </a-radio-button>
            <a-radio-button value="b" @click="getLineChart(30)">
              近30天
            </a-radio-button>
          </a-radio-group>
        </div>
        <div style="width: 100%; text-align: center">
          <div ref="lineChart" id="lineChart"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ChartTitle from "../../Components/ChartTitle";
import NumberCount from "../../Components/NumberCount";

export default {
  components: {
    ChartTitle,
    NumberCount,
  },
  data() {
    return {
      userName: "",
      lockList: [],
      opened: 0,
      closed: 0,
      // 折线图数据
      date: [],
      openCount: [],
      closeCount: [],
      // 骨架屏关闭时间
      isClose: false
    };
  },
  computed: {
    total() {
      return this.opened + this.closed;
    },
  },
  mounted() {
    this.userName = this.$_cookie.getCookie("user");
    if(this.userName){
      this.isClose = true;
      this.getPieChart();
      this.getTopChart();
      this.getLineChart(7);
    }
  },

  methods: {
    // 绘制饼图
    async getPieChart() {
      const _this = this;
      // 获取门锁统计数据
      this.username = this.$_cookie.getCookie("user");
      const data = {
        username: this.username,
      };
      const res = await this.$_api.getLockByUsername(data);
      if (res.data.data.list) {
        this.lockList = res.data.data.list;
        this.opened = this.lockList.filter((item) => item.state == 1).length;
        this.closed = this.lockList.filter((item) => item.state == 0).length;
      }
      // 绘制图形
      const chart = this.$refs.chart;
      if (chart) {
        const myChart = this.$echarts.init(chart);
        const option = {
          title: {
            // text: "门锁使用概况统计",
            // subtext: `当前使用者拥有${_this.lockList.length}把锁`,
            left: "center",
            textStyle: {
              fontSize: 22,
              fontFamily: "sans-serif",
            },
          },
          tooltip: {
            trigger: "item",
            formatter: "{b} : {c} ({d}%)",
          },
          legend: {
            bottom: 10,
            left: "center",
            data: ["已开启", "已关闭"],
          },
          series: [
            {
              type: "pie",
              radius: "65%",
              center: ["50%", "50%"],
              selectedMode: "single",
              data: [
                {
                  value: _this.opened,
                  name: "已开启",
                  itemStyle: { color: "#63a5ef" },
                },
                {
                  value: _this.closed,
                  name: "已关闭",
                  itemStyle: { color: "lightgray" },
                },
              ],
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: "rgba(0, 0, 0, 0.5)",
                },
              },
            },
          ],
        };
        myChart.setOption(option);
        window.onresize = function () {
          myChart.resize();
        };
      }
    },

    // 绘制频繁操作图
    async getTopChart() {
      const chart = this.$refs.top;
      if (chart) {
        // 先获取数据
        const data = {
          username: this.userName,
          identityId: undefined,
          timestart: undefined,
          timeend: undefined,
          current: 1,
          limit: 20000,
        };
        const res = await this.$_api.getAllLoggers(data);
        const loggerData = res.data.data.list.records;
        // 先抽取所有出现过的identityId
        let ids = [];
        loggerData.forEach((item) => {
          ids.push(item.lockid);
        });

        // 获取键值对中的key
        const countKey = Array.from(new Set(ids));
        const countObj = {};
        countKey.forEach((item) => {
          countObj[item] = 0;
        });

        // 统计
        ids.forEach((item) => countObj[item]++);

        // 进行排序
        let valSorted = Object.values(countObj)
          .sort((a, b) => {
            return b - a;
          })
          .slice(0, 5);

        // 找到对应的key值，然后push进去
        let keySorted = [];
        for (let i = 0; i < valSorted.length; i++) {
          keySorted.push(this.findKey(countObj, valSorted[i]));
        }

        // keySorted和valSorted是最后需要的结果
        console.log(keySorted);
        console.log(valSorted);

        const myChart = this.$echarts.init(chart);

        const option = {
          title: {
            // text: "世界人口总量",
            // subtext: "数据来自网络",
          },
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "shadow",
            },
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
          },
          xAxis: {
            show: false,
            type: "value",
            barGap: "10%",
            // boundaryGap: false,
            axisLabel: {
              textStyle: {
                color: "#000",
                fontSize: "14",
                itemSize: "",
              },
            },
          },
          yAxis: {
            // boundaryGap: false,
            type: "category",
            data: keySorted.reverse(),
            axisLabel: {
              textStyle: {
                color: "#000",
                fontSize: "14",
                itemSize: "",
              },
            },
          },
          series: [
            {
              name: "操作总次数",
              type: "bar",
              data: valSorted.reverse(),
              barCategoryGap: "10%",
              barWidth: 30,
            },
            // {
            //   name: "2012年",
            //   type: "bar",
            //   data: [19325, 23438, 31000, 121594, 134141, 681807],
            // },
          ],
        };
        myChart.setOption(option);
        window.onresize = function () {
          myChart.resize();
        };
      }
    },

    findKey(obj, value, compare = (a, b) => a === b) {
      return Object.keys(obj).find((k) => compare(obj[k], value));
    },
    // 绘制条形图
    async getLineChart(count) {
      this.date = [];
      this.openCount = [];
      this.closeCount = [];
      // 获取数据
      await this.getLineData(count);

      const chart = this.$refs.lineChart;
      if (chart) {
        const myChart = this.$echarts.init(chart);
        // 处理数据
        const dataSource = [];
        const length = this.date.length;
        for (let i = 0; i < length; i++) {
          const obj = {};
          obj.date = this.date.pop();
          obj.open = this.openCount.pop();
          obj.close = this.closeCount.pop();
          dataSource.push(obj);
        }
        const option = {
          legend: {},
          tooltip: {},
          dataset: {
            dimensions: ["date", "open", "close"],
            source: dataSource,
          },
          xAxis: { type: "category" },
          yAxis: { type: "value" },
          series: [
            {
              name: "开锁次数",
              type: "bar",
              itemStyle: { color: "#63a5ef" },
            },
            {
              name: "关锁次数",
              type: "bar",
              itemStyle: { color: "#f79969" },
            },
          ],
        };
        myChart.setOption(option);
        window.onresize = function () {
          myChart.resize();
        };
      }

      // 原始折线图，先保留
      // const chart = this.$refs.lineChart;
      // if (chart) {
      //   const myChart = this.$echarts.init(chart);

      //   const option = {
      //     legend: {
      //       data: ["开锁总次数", "关锁总次数"],
      //     },
      //     xAxis: {
      //       type: "category",
      //       data: this.date.reverse(),
      //     },
      //     yAxis: {
      //       type: "value",
      //     },
      //     // 设置是否显示提示
      //     tooltip: {
      //       trigger: "axis",
      //     },
      //     series: [
      //       {
      //         name: "开锁总次数",
      //         data: this.openCount.reverse(),
      //         type: "line",
      //       },
      //       {
      //         name: "关锁总次数",
      //         data: this.closeCount.reverse(),
      //         type: "line",
      //         itemStyle: { color: "rgb(201, 40, 40)" },
      //       },
      //     ],
      //   };
      //   myChart.setOption(option);
      //   window.onresize = function() {
      //     myChart.resize();
      //   };
      // }
    },
    async getLineData(count) {
      const data = {
        username: this.userName,
        identityId: undefined,
        timestart: undefined,
        timeend: undefined,
        current: 1,
        limit: 20000,
      };

      // 获取数据
      const res = await this.$_api.getAllLoggers(data);
      const loggerData = res.data.data.list.records;
      for (let i = 0; i < count; i++) {
        // 比较对象
        let comparedDate = new Date(new Date() - 24 * 60 * 60 * 1000 * i);
        this.date.push(this.transferTime(comparedDate));
        let filterRes = loggerData.filter(
          (item) =>
            this.transferTime(new Date(item.time)) ==
              this.transferTime(comparedDate) &&
            item.openstate == 1 &&
            item.success == 1
        );
        this.openCount.push(filterRes.length);
      }

      for (let i = 0; i < count; i++) {
        // 比较对象
        let comparedDate = new Date(new Date() - 24 * 60 * 60 * 1000 * i);
        let filterRes = loggerData.filter(
          (item) =>
            this.transferTime(new Date(item.time)) ==
              this.transferTime(comparedDate) &&
            item.openstate == 0 &&
            item.success == 1
        );
        this.closeCount.push(filterRes.length);
      }
    },
    // 日期转换格式
    transferTime(obj) {
      return obj.getMonth() + 1 + "-" + obj.getDate();
    },
  },
};
</script>
<style lang="less" scoped>
.usage-box-content {
  width: 100%;
  display: flex;
}

.pie {
  width: 50%;
  height: 376px;
  display: inline-block;
  /* left: 0; */
}
.discription {
  flex: 1;

  display: flex;
  flex-direction: column;
  justify-content: center;

  &-item1 {
    font-size: 18px;

    &-count {
      color: rgb(255, 81, 0);
    }
  }
  &-item2 {
    font-size: 18px;
    margin-top: 20px;

    &-count {
      color: #0469c9;
    }
  }
}
.operate-top {
  margin: 30px 0 0 0;
}
.situation {
  margin: 30px 0;
}

#lineChart {
  width: 1000px;
  height: 376px;
  margin: 0 auto;
  color: #b1b1b1;
}
#top-chart {
  width: 1000px;
  height: 350px;
  margin: 0 auto;
  position: relative;
  top: -10px;
}
</style>
